package com.voilet.interview.open.glide.load.engine;

import android.support.annotation.NonNull;
import android.support.v4.util.Pools.Pool;

import com.voilet.interview.open.glide.load.Options;
import com.voilet.interview.open.glide.load.data.DataRewinder;
import com.voilet.interview.open.glide.util.Preconditions;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * For a given {@link com.voilet.interview.open.glide.load.data.DataFetcher} for a given data class, attempts to
 * fetch the data and then run it through one or more
 * {@link com.voilet.interview.open.glide.load.engine.DecodePath}s.
 * 根据给定的数据类型的DataFetcher尝试获取数据，然后尝试通过一个或多个decodePath进行decode。
 * decode＋transcode的处理流程称为decodePath。LoadPath是对decodePath的封装，持有一个decodePath的List。
 * 在通过modelloader.fetchData获取到data后，会对data进行decode，具体的decode操作就是通过loadPath来完成。
 * resourceClass就是asBitmap，asDrawable方法的参数。
 *
 * @param <Data>         The type of data that will be fetched.
 * @param <ResourceType> The type of intermediate resource that will be decoded within one of the
 *                       {@link com.voilet.interview.open.glide.load.engine.DecodePath}s.
 * @param <Transcode>    The type of resource that will be returned as the result if the load and
 *                       one of the decode paths succeeds.
 */
public class LoadPath<Data, ResourceType, Transcode> {
    private final Class<Data> dataClass;
    private final Pool<List<Throwable>> listPool;
    private final List<? extends DecodePath<Data, ResourceType, Transcode>> decodePaths;
    private final String failureMessage;

    public LoadPath(Class<Data> dataClass, Class<ResourceType> resourceClass,
                    Class<Transcode> transcodeClass,
                    List<DecodePath<Data, ResourceType, Transcode>> decodePaths, Pool<List<Throwable>> listPool) {
        this.dataClass = dataClass;
        this.listPool = listPool;
        this.decodePaths = Preconditions.checkNotEmpty(decodePaths);
        failureMessage = "Failed LoadPath{" + dataClass.getSimpleName() + "->"
                + resourceClass.getSimpleName() + "->" + transcodeClass.getSimpleName() + "}";
    }

    public Resource<Transcode> load(DataRewinder<Data> rewinder, @NonNull Options options, int width,
                                    int height, DecodePath.DecodeCallback<ResourceType> decodeCallback) throws GlideException {
        List<Throwable> throwables = Preconditions.checkNotNull(listPool.acquire());
        try {
            return loadWithExceptionList(rewinder, options, width, height, decodeCallback, throwables);
        } finally {
            listPool.release(throwables);
        }
    }

    private Resource<Transcode> loadWithExceptionList(DataRewinder<Data> rewinder,
                                                      @NonNull Options options,
                                                      int width, int height, DecodePath.DecodeCallback<ResourceType> decodeCallback,
                                                      List<Throwable> exceptions) throws GlideException {
        Resource<Transcode> result = null;
        //noinspection ForLoopReplaceableByForEach to improve perf
        for (int i = 0, size = decodePaths.size(); i < size; i++) {
            DecodePath<Data, ResourceType, Transcode> path = decodePaths.get(i);
            try {
                result = path.decode(rewinder, width, height, options, decodeCallback);
            } catch (GlideException e) {
                exceptions.add(e);
            }
            if (result != null) {
                break;
            }
        }

        if (result == null) {
            throw new GlideException(failureMessage, new ArrayList<>(exceptions));
        }

        return result;
    }

    public Class<Data> getDataClass() {
        return dataClass;
    }

    @Override
    public String toString() {
        return "LoadPath{" + "decodePaths=" + Arrays.toString(decodePaths.toArray()) + '}';
    }
}
